package exam;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    //用户名
    private static final String USERNAME = "admin";
    //密码
    private static final String PASSWORD = "admin";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        //获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String type = request.getParameter("type");

        if (USERNAME.equals(username) && PASSWORD.equals(password)) {
            //密码正确且登录目的是制作答案，即类型为1
            if (type.equals("1")) {
                request.getRequestDispatcher("make_answer.html").forward(request, response);
                //密码正确且登录目的是查看得分结果，即类型为2
            } else if (type.equals("2")) {
                request.getRequestDispatcher("ResultServlet").forward(request, response);
            }
        } else {
            //登陆失败，提示用户并返回主页
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><title>登陆失败</title></head>");
            out.println("<body>");
            out.println("<script>");
            out.println("window.alert('"+"用户名或密码错误"+"');window.location.href='./homepage.html'");
            out.println("</script>");
            out.println("</body></html>");
            out.close();
        }
    }
}
